package com.example.ymm.modules1.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.model.em.EmSysNotePlatform;
import com.example.ymm.modules1.entity.my.user.*;
import com.example.ymm.modules1.mapper.my.user.DbCardMapper;
import com.example.ymm.modules1.query.DbUserAdvanceDateQueryCriteria;
import com.example.ymm.modules1.service.dto.*;
import com.example.ymm.modules1.service.user.*;
import com.example.ymm.util.*;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.*;

@Service
@Transactional
@Slf4j
public class DbCardServiceImpl extends BaseServiceImpl<DbCardMapper, DbCard> implements DbCardService {

    @Autowired
    DbUserService dbUserService;
    @Autowired
    DbUserAdvanceDateService dbUserAdvanceDateService;
    @Autowired
    DbIntegralLogService dbIntegralLogService;

    @Autowired
    DbUserNoteService dbUserNoteService;

    @Override
    public TableList<DbCard> list(DbCardQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DbCard> page = new Page<DbCard>(pageDto.getPage(), pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DbCard.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<DbCard> tableList = new TableList(page);
        return tableList;
    }

    public List<DbCard> queryAll(DbCardQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DbCard.class, criteria);
        predicate.orderByDesc("create_time");
        List<DbCard> result = baseMapper.selectList(predicate);
        return result;
    }


    @Override
    public DbCard queryYesterdayCardByUserId(String userId) {
        Date yesterday = DateKit.getYesterday();
        String yes = DateKit.dateFormat(yesterday, "yyyy-MM-dd");
//        String yes = DateUtils.getDateStrByBefore8_30Yesday();
        if("2025-04-10".equals(yes)){
            yes="2025-04-09";
        }
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setUserId(userId);
        criteria.setDay(yes);
        DbCard dbCard = null;
        List<DbCard> dbCards = queryAll(criteria);
        if (UtilValidate.isNotEmpty(dbCards)) {
            dbCard = dbCards.get(0);
            if ("补卡".equals(dbCard.getNote())) {
                dbCard = null;
            }
        }
        return dbCard;
    }

    @Override
    public DbCard queryAdvanceYesterdayByDate(String userId, String date) {
        Date dateFormat = DateKit.dateFormat(date + " 01:00:00");
        Date yesterday = DateKit.getYesterday(dateFormat);
        String yes = DateKit.dateFormat(yesterday, "yyyy-MM-dd");
//        String yes = DateUtils.getDateStrByBefore8_30Yesday();

        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setUserId(userId);
        criteria.setDay(yes);
        DbCard dbCard = null;
        List<DbCard> dbCards = queryAll(criteria);
        if (UtilValidate.isNotEmpty(dbCards)) {
            dbCard = dbCards.get(0);
            if ("补卡".equals(dbCard.getNote())) {
                dbCard = null;
            }
        }
        return dbCard;
    }

    @Override
    public DbCard queryTodayCardByUserId(String userId) {
        Date now = new Date();
        String day = DateKit.dateFormat(now, "yyyy-MM-dd");
//        String day = DateUtils.getDateStrByBefore8_30();

        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setUserId(userId);
        criteria.setDay(day);
        DbCard dbCard = null;
        List<DbCard> dbCards = queryAll(criteria);
        if (UtilValidate.isNotEmpty(dbCards)) {
            dbCard = dbCards.get(0);
        }
        return dbCard;
    }


    @Override
    public DbCard queryDateCardByUserId(String userId, String date) {

        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setUserId(userId);
        criteria.setDay(date);
        DbCard dbCard = null;
        List<DbCard> dbCards = queryAll(criteria);
        if (UtilValidate.isNotEmpty(dbCards)) {
            dbCard = dbCards.get(0);
        }
        return dbCard;
    }

    @Override
    public DbCard queryFullMonth(String userId, String month) {
        LambdaQueryWrapper<DbCard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DbCard::getUserId, userId)
                .eq(DbCard::getMonth, month).eq(DbCard::getIsFullMonth, 1);
        List<DbCard> dbCards = baseMapper.selectList(queryWrapper);
        DbCard result = null;
        if (UtilValidate.isNotEmpty(dbCards)) {
            result = dbCards.get(0);
        }
        return result;
    }


    @Override
    public DbCard addCard() {
        Date now = new Date();
        String day = DateKit.dateFormat(now, "yyyy-MM-dd");
        String month = DateKit.dateFormat(now, "yyyy-MM");
        String year = DateKit.dateFormat(now, "yyyy");

        String userId = getUserId();
        String userName = getUserName();
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setDay(day);
        criteria.setUserId(userId);
        // DateKit.getLastMonthBegin()
        // 获取当前年月
        YearMonth yearMonth = YearMonth.now();
        // 获取这个月有多少天
        int countMonthDays = yearMonth.lengthOfMonth();


        //统计 这个月的打卡天数 不连续
        Integer dayCount = countDaysContinuous(userId, month);


        //统计 这年的打卡月数 不连续
        Integer monthCount = countMonthsContinuous(userId, year);

        List<DbCard> dbCards = queryAll(criteria);
        DbCard card = null;
        if (UtilValidate.isEmpty(dbCards)) {
            card = new DbCard();
            card.setDay(day);
            card.setMonth(month);
            card.setYear(year);
            card.setUserId(userId);
            card.setUserName(userName);
            Timestamp countTime = new Timestamp(now.getTime());
            card.setCountTime(countTime);
            //判断是否月 满勤 全勤

            //月 满勤 24 天 并且 要没有满勤过

            DbCard fullMonth = queryFullMonth(userId, month);
            card.setIsFullMonth(0);
            if ((dayCount + 1) >= 24 && UtilValidate.isEmpty(fullMonth)) {
                card.setIsFullMonth(1);
            }
            //月 全勤 所有天 天
            card.setIsAllMonth(0);
            if ((dayCount + 1) >= countMonthDays) {
                card.setIsAllMonth(1);
            }
            //判断是否年 满勤 全勤

            //年 满勤 10 个月
            card.setIsFullYear(0);
            if ((monthCount + 1) >= 10) {
                card.setIsFullYear(1);
            }
            //月 全勤 12个月
            card.setIsAllYear(0);
            if ((monthCount + 1) == 12) {
                card.setIsAllYear(1);
            }
            saveOrUpdate(card);
        } else {
            card = dbCards.get(0);
        }
        return card;
    }

    ;


    @Override
    public Integer getTodayPatchCards() {
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        String userId = getUserId();
        criteria.setUserId(userId);
        List<String> dateList = DateUtils.getDateListByThisDay();
        criteria.setTimes(dateList);
        criteria.setNote("补卡");
        Integer todayPatchCardCount = baseMapper.getTodayPatchCardCount(criteria);
        return todayPatchCardCount;
    }

    @Override
    public DbCard addCardByDate(String date) {
        Date now = new Date();
        now = DateKit.dateFormat(DateKit.dateFormat(now, date + " HH:mm:ss"));
        String day = date;
        String month = DateKit.dateFormat(now, "yyyy-MM");
        String year = DateKit.dateFormat(now, "yyyy");

        String userId = getUserId();
        String userName = getUserName();
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setDay(day);
        criteria.setUserId(userId);


        List<DbCard> dbCards = queryAll(criteria);
        DbCard card = null;
        if (UtilValidate.isEmpty(dbCards)) {
            card = new DbCard();
            card.setDay(day);
            card.setMonth(month);
            card.setYear(year);
            card.setUserId(userId);
            card.setUserName(userName);
            card.setNote("补卡");
            Timestamp countTime = new Timestamp(now.getTime());
            card.setCountTime(countTime);


            //判断是否月 满勤 全勤

            //统计 这个月的打卡天数 不连续
            Integer dayCount = countDaysContinuous(userId, month);
            // 获取当前年月
            YearMonth yearMonth = YearMonth.now();
             // 获取这个月有多少天
            int countMonthDays = yearMonth.lengthOfMonth();

            //统计 这年的打卡月数 不连续
            Integer monthCount = countMonthsContinuous(userId, year);
            //月 满勤 24 天 并且 要没有满勤过

            DbCard fullMonth = queryFullMonth(userId, month);
            card.setIsFullMonth(0);
            if ((dayCount + 1) >= 24 && UtilValidate.isEmpty(fullMonth)) {
                card.setIsFullMonth(1);
            }
            //月 全勤 所有天 天
            card.setIsAllMonth(0);
            if ((dayCount + 1) >= countMonthDays) {
                card.setIsAllMonth(1);
            }
            //判断是否年 满勤 全勤

            //年 满勤 10 个月
            card.setIsFullYear(0);
            if ((monthCount + 1) >= 10) {
                card.setIsFullYear(1);
            }
            //月 全勤 12个月
            card.setIsAllYear(0);
            if ((monthCount + 1) == 12) {
                card.setIsAllYear(1);
            }

            saveOrUpdate(card);
        } else {
            card = dbCards.get(0);
        }
        return card;
    }


    @Override
    public DbCard addAdvanceCardByDate(String date) {
        Date now = new Date();
        now = DateKit.dateFormat(DateKit.dateFormat(now, date + " HH:mm:ss"));
        String day = date;
        String month = DateKit.dateFormat(now, "yyyy-MM");
        String year = DateKit.dateFormat(now, "yyyy");

        String userId = getUserId();
        String userName = getUserName();
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setDay(day);
        criteria.setUserId(userId);


        List<DbCard> dbCards = queryAll(criteria);
        DbCard card = null;
        if (UtilValidate.isEmpty(dbCards)) {
            card = new DbCard();
            card.setDay(day);
            card.setMonth(month);
            card.setYear(year);
            card.setUserId(userId);
            card.setUserName(userName);
            card.setNote("提前读书");
            Timestamp countTime = new Timestamp(now.getTime());
            card.setCountTime(countTime);
            saveOrUpdate(card);
        } else {
            card = dbCards.get(0);
        }
        return card;
    }

    @Override
    public DbCard addSysCardByDate(String userId, String date) {
//        String userId = card.getUserId();
        DbUser user = dbUserService.getById(userId);
        Date now = new Date();
        now = DateKit.dateFormat(DateKit.dateFormat(now, date + " HH:mm:ss"));
        String day = date;
        String month = DateKit.dateFormat(now, "yyyy-MM");
        String year = DateKit.dateFormat(now, "yyyy");

        DbCard card = new DbCard();
        card.setDay(date);
        card.setMonth(month);
        card.setYear(year);
        card.setUserId(userId);
        card.setUserName(user.getUserName());
        card.setNote("补卡");
        card.setRemark("因程序原因造成无法提交，现进行补偿!");
        Timestamp countTime = new Timestamp(now.getTime());
        card.setCountTime(countTime);
        saveOrUpdate(card);
        //积分
        DbIntegralLog integralLog=new DbIntegralLog();
        //integral
        integralLog.setIntegral(1);
        integralLog.setReadType(2);
        integralLog.setUserId(user.getUserId());
        integralLog.setUserName(user.getUserName());
        integralLog.setType(1);
        integralLog.setDay(day);
        dbIntegralLogService.saveOrUpdate(integralLog);
        Integer integral=null;
        String note="";
        DbUser n_user=new DbUser();
        Integer continuousNum=user.getContinuousNum()+1;
        if(continuousNum.equals(10)){
            integral=10;
            note="连续签到获得";
        }
        if(continuousNum==20){
            integral=20;
            note="连续签到获得";
        }
        if(continuousNum>20) {

            continuousNum = 1;
        }
        n_user.setContinuousNum(continuousNum);
        n_user.setUserId(userId);
        n_user.setIntegral(user.getIntegral()+1);
        dbUserService.updateById(n_user);

        //有连续签到
        if(UtilValidate.isNotEmpty(note)){
            DbIntegralLog i1=new DbIntegralLog();
            //integral
            i1.setIntegral(integral);
            i1.setReadType(3);
            i1.setUserId(user.getUserId());
            i1.setUserName(user.getUserName());
            i1.setNote(note);
            i1.setType(1);
            i1.setDay(day);
            i1.setSysNote(EmSysNotePlatform.da_day.getType());
            dbIntegralLogService.saveOrUpdate(i1);
        }
        return card;
    }

    @Override
    public DbCard addUserCardByDate(String userId, String date, int integral,String sysNote) {
        DbUser user = dbUserService.getById(userId);
        Date now = new Date();
        now = DateKit.dateFormat(DateKit.dateFormat(now, date + " HH:mm:ss"));
        String day = DateKit.dateFormat(now,"yyyy-MM-dd");
        String month = DateKit.dateFormat(now, "yyyy-MM");
        String year = DateKit.dateFormat(now, "yyyy");
        Integer readType=2;

        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setDay(day);
        criteria.setUserId(userId);
        DbCard card =null;
        List<DbCard> dbCards = queryAll(criteria);
        if (UtilValidate.isEmpty(dbCards)) {

            card = new DbCard();
            card.setDay(day);
            card.setMonth(month);
            card.setYear(year);
            card.setUserId(userId);
            card.setUserName(user.getUserName());
            card.setRemark("因程序原因造成无法提交，现进行补偿!");
            Timestamp countTime = new Timestamp(now.getTime());
            card.setCountTime(countTime);
            saveOrUpdate(card);

            //积分
            DbIntegralLog integralLog=new DbIntegralLog();
            //integral
            integralLog.setIntegral(integral);
            integralLog.setReadType(readType);
            integralLog.setUserId(user.getUserId());
            integralLog.setUserName(user.getUserName());
            integralLog.setType(1);
            integralLog.setDay(day);
            integralLog.setSysNote(sysNote);
            dbIntegralLogService.saveOrUpdate(integralLog);

            DbUser n_user=new DbUser();
            Integer continuousNum=user.getContinuousNum()+1;
//            n_user.setContinuousNum(continuousNum);
            n_user.setUserId(userId);
            n_user.setIntegral(user.getIntegral()+integral);
//            dbUserService.updateById(n_user);

            String note="";
            if(continuousNum.equals(10)){
                integral=10;
                note="连续签到获得";
            }
            if(continuousNum==20){
                integral=20;
                note="连续签到获得";
            }
            if(continuousNum>20) {

                continuousNum = 1;
            }
            n_user.setContinuousNum(continuousNum);
            n_user.setIntegral(n_user.getIntegral()+integral);
            dbUserService.updateById(n_user);

            //有连续签到
            if(UtilValidate.isNotEmpty(note)){
                DbIntegralLog i1=new DbIntegralLog();
                //integral
                i1.setIntegral(integral);
                i1.setReadType(3);
                i1.setUserId(user.getUserId());
                i1.setUserName(user.getUserName());
                i1.setNote(note);
                i1.setType(1);
                i1.setDay(day);
                i1.setSysNote(EmSysNotePlatform.da_day.getType());
                dbIntegralLogService.saveOrUpdate(i1);
            }
        }



        return card;
    }

    @Override
    public DbCard addSysCardByNow(String userId,int integral) {
        DbUser user = dbUserService.getById(userId);
        Date now = new Date();
//        now = DateKit.dateFormat(DateKit.dateFormat(now, date + " HH:mm:ss"));
        String day = DateKit.dateFormat(now,"yyyy-MM-dd");
        String month = DateKit.dateFormat(now, "yyyy-MM");
        String year = DateKit.dateFormat(now, "yyyy");
        Integer readType=2;

        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setDay(day);
        criteria.setUserId(userId);
        DbCard card =null;
        List<DbCard> dbCards = queryAll(criteria);
        if (UtilValidate.isEmpty(dbCards)) {

            card = new DbCard();
            card.setDay(day);
            card.setMonth(month);
            card.setYear(year);
            card.setUserId(userId);
            card.setUserName(user.getUserName());

            card.setRemark("因程序原因造成无法提交，现进行补偿!");
            Timestamp countTime = new Timestamp(now.getTime());
            card.setCountTime(countTime);
            saveOrUpdate(card);

            //积分
            DbIntegralLog integralLog=new DbIntegralLog();
            //integral
            integralLog.setIntegral(integral);
            integralLog.setReadType(readType);
            integralLog.setUserId(user.getUserId());
            integralLog.setUserName(user.getUserName());
            integralLog.setType(1);

            dbIntegralLogService.saveOrUpdate(integralLog);

            DbUser n_user=new DbUser();
            Integer continuousNum=user.getContinuousNum()+1;
            n_user.setContinuousNum(continuousNum);
            n_user.setUserId(userId);
            n_user.setIntegral(user.getIntegral()+integral);
            dbUserService.updateById(n_user);
        }



        return card;
    }

    /**
     * @param dbUsers group.totalType 统计方式 1 从起始日期开始统计 2 当前月份 3 按当年统计
     * @return
     */
    @Override
    public List<DbUser> countUserCardByGroup(List<DbUser> dbUsers, DbChatGroup group) {


//        String day = DateKit.dateFormat(DateKit.getYesterday(), "yyyy-MM-dd");
        List<String> stringList = getStartEndTime(group.getTotalType(), group.getStartDate());

        dbUsers.forEach(e -> {
            DbCardQueryCriteria criteria = new DbCardQueryCriteria();
            criteria.setUserId(e.getUserId());
            criteria.setTimes(stringList);
//            criteria.setDay(day);
            Long dayCount = baseMapper.getDayCount(criteria);
            if (UtilValidate.isEmpty(dayCount)) {
                dayCount = 0l;
            }
            e.setCardNums(dayCount.intValue());
        });
        List<DbUser> u1 = new ArrayList<>();
        List<DbUser> u2 = new ArrayList<>();
        dbUsers.forEach(r -> {
            if (UtilValidate.isNotEmpty(r.getSort())) {
                u1.add(r);
            } else {
                u2.add(r);
            }
        });
        u1.sort(new Comparator<DbUser>() {
            @Override
            public int compare(DbUser o1, DbUser o2) {
                return o2.getSort() - o1.getSort();
            }
        });
        u2.sort(new Comparator<DbUser>() {
            @Override
            public int compare(DbUser o1, DbUser o2) {
                return o2.getCardNums() - o1.getCardNums();
            }
        });
        u1.addAll(u2);
//        List<String> userIds=new ArrayList<>();
//        dbUsers.forEach(r->{
//            userIds.add(r.getUserId());
//        });
//        DbCardQueryCriteria criteria=new DbCardQueryCriteria();
//        criteria.setUserIdIn(userIds);
//        criteria.setTimes(stringList);
//        List<DbUser> result = baseMapper.getMobileDayCount(criteria);
        return u1;
    }

    /**
     * 统计方式 1 从起始日期开始统计 2 当前月份 3 按当年统计
     * startDateStr 指定的起始日期
     *
     * @param totalType
     * @param startDateStr
     * @return
     */
    public List<String> getStartEndTime(Integer totalType, String startDateStr) {
        String startDateTime = "";
        String startDate = "";
        // 8.30
//        String endDateTime=DateKit.getStringNowTime();
//        String endDateTime=DateKit.getYesterdayYmd();

        // 今天  00:00:00
        Date now = new Date();
//        String endDateTime = DateKit.dateFormat(now, "yyyy-MM-dd 00:00:00");
        String endDateTime = DateKit.dateFormat(now, "yyyy-MM-dd 08:30:00");
        switch (totalType) {
            case 1:
                startDate = startDateStr;
                break;
            case 2:
                startDate = DateKit.getThisMonthStartDate();
                endDateTime = DateKit.getThisMonthEndDate()+" 23:59:59";
                break;
            case 3:
                startDate = DateKit.getThisYearStartDate();
                break;
        }
        startDateTime = startDate + " 00:00:00";
        List<String> stringList = new ArrayList<>();
        stringList.add(startDateTime);
        stringList.add(endDateTime);
        return stringList;
    }


    /**
     * 排行版日期处理
     * totalType  2 月份 3 年
     * startDateStr 日期字符串
     *
     * @param totalType
     * @param startDateStr
     * @return
     */
    public List<String> getRankingStartEndTime(Integer totalType, String startDateStr) {
        String startDateTime = "";
        String startDate = "";
        String endDateTime = "";

        switch (totalType) {
            case 1:
                startDate = startDateStr;
                break;
            case 2:
                startDate = startDateStr + "-01";
                endDateTime = startDateStr + "-31";
                break;
            case 3:
                String[] split = startDateStr.split("-");
                startDate = split[0] + "-01-01";
                endDateTime = split[0] + "-12-31";
                break;
        }
        startDateTime = startDate + " 00:00:00";
        endDateTime = endDateTime + " 23:59:59";
        List<String> stringList = new ArrayList<>();
        stringList.add(startDateTime);
        stringList.add(endDateTime);
        return stringList;
    }

    /**
     * 排行版日期处理
     * totalType  2 月份 3 年
     *
     * @param totalType
     * @param startDateStr
     * @return
     */
    public String getRankingStr(Integer totalType, String startDateStr) {

        String str = "";
        String[] split = startDateStr.split("-");
        str = startDateStr;
        switch (totalType) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                str = split[0];
                break;
        }

        return str;
    }


    public List<DbUser> getRankings(Integer totalType, String date_str) {
//        List<String> times=getRankingStartEndTime(totalType,date_str);
        String rankingStr = getRankingStr(totalType, date_str);
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        if (totalType == 2) {
            criteria.setMonth(rankingStr);
        } else if (totalType == 3) {
            criteria.setYear(rankingStr);
        } else {
            criteria.setMonth(rankingStr);
        }


//        criteria.setTimes(times);
        List<DbUser> rankings = baseMapper.getRankings(criteria);
//        List<DbUser> u1=new ArrayList<>();
//        List<DbUser> u2=new ArrayList<>();
//        rankings.forEach(r->{
//            if(UtilValidate.isNotEmpty(r.getSort())){
//                u1.add(r);
//            }else{
//                u2.add(r);
//            }
//        });
//        u1.sort(new Comparator<DbUser>() {
//            @Override
//            public int compare(DbUser o1, DbUser o2) {
//                return o2.getSort()-o1.getSort();
//            }
//        });
//        u2.sort(new Comparator<DbUser>() {
//            @Override
//            public int compare(DbUser o1, DbUser o2) {
//                return o2.getCardNums()-o1.getCardNums();
//            }
//        });
//        u1.addAll(u2);
        return rankings;
    }


    @Override
    public Integer getThisMonthRankings() {
        Integer rankingNum = null;
        Date now = new Date();
        String month = DateKit.dateFormat(now, "yyyy-MM");
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setMonth(month);
        YmPageDto pageDto = new YmPageDto();
        pageDto.setPage(1);
        pageDto.setPageSize(5);
        getPage(pageDto);
        List<DbUser> rankings = baseMapper.getRankings(criteria);
        // System.out.println("--rankings:"+rankings.toString());
        String userId = getUserId();
        for (int a = 0; a < rankings.size(); a++) {
            DbUser dbUser = rankings.get(a);
            if (dbUser.getUserId().equals(userId)) {
                rankingNum = a + 1;
                break;
            }
        }
        //    System.out.println("--rankingNum:"+rankingNum);
        return rankingNum;
    }


    /**
     * 测试排行
     * @param userId
     * @return
     */
    @Override
    public Integer getThisMonthRankingsTest(String userId) {
        Integer rankingNum = null;
        Date now = new Date();
        String month = DateKit.dateFormat(now, "yyyy-MM");
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setMonth(month);
        YmPageDto pageDto = new YmPageDto();
        pageDto.setPage(1);
        pageDto.setPageSize(5);
        getPage(pageDto);
        List<DbUser> rankings = baseMapper.getRankings(criteria);
        // System.out.println("--rankings:"+rankings.toString());

        for (int a = 0; a < rankings.size(); a++) {
            DbUser dbUser = rankings.get(a);
            if (dbUser.getUserId().equals(userId)) {
                rankingNum = a + 1;
                break;
            }
        }
        //    System.out.println("--rankingNum:"+rankingNum);
        return rankingNum;
    }

    @Override
    public Integer countDaysContinuous(String userId, String month) {
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setMonth(month);
        criteria.setUserId(userId);
        Integer result = 0;
        Long dayCount = baseMapper.getDayCount(criteria);
        if (UtilValidate.isNotEmpty(dayCount)) {
            result = dayCount.intValue();
        }
//        List<String> days = baseMapper.getDayListCount(criteria);
//        int result = SignInCounter.getThisMonthSignInDays(days, month);
        return result;
    }

    @Override
    public Integer countMonthsContinuous(String userId, String year) {
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setYear(year);
        criteria.setUserId(userId);
        Integer result = 0;
        result = baseMapper.getMonthCount(criteria);
        if (UtilValidate.isEmpty(result)) {
            result = 0;
        }
        return result;
    }


    @Override
    public TableList<SysRankingListDto> sysRankingList(SysRankingQueryCriteria criteria, YmPageDto pageDto) {
        getPage(pageDto);
        List<SysRankingListDto> maps = baseMapper.sysRankingList(criteria);
        PageInfo<SysRankingListDto> pageInfo = new PageInfo<>(maps);
        TableList<SysRankingListDto> tableList = new TableList<>(pageInfo);
        return tableList;
    }


    @Override
    public void testFn() {
        String userId = "2363192520970306";
        List<String> times = DateUtils.fourDayBefore();
        System.out.println(times);
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setUserId(userId);
        criteria.setTimes(times);
        List<String> dayListCount = baseMapper.getDayListCount(criteria);
        System.out.println(dayListCount);
        for (int i = 0; i < times.size(); i++) {
            for (int a = 0; a < dayListCount.size(); a++) {
                if (times.get(i).equals(dayListCount.get(a))) {
                    times.remove(i);
                }
            }
        }
        System.out.println(times);
    }


    @Override
    public List<String> getLackCards() {
        String userId = getUserId();
    //    List<String> times = DateUtils.fourDayBefore();//获取4天前到 现在的开始和截止时间
        List<String> times = DateUtils.monthBetweenArr();
//
//        Integer todayPatchCards = getTodayPatchCards();
//        //今天如果有补卡就不能再补了，一天最多只能补一次
//        if(UtilValidate.isNotEmpty(todayPatchCards)&&todayPatchCards>0){
//            List<String> result=new ArrayList<>();
//            return result;
//        }
//        System.out.println(times);
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setUserId(userId);
        criteria.setTimes(times);
        //查询出有打卡的日期
        List<String> dayListCount = baseMapper.getDayListCount(criteria);
        System.out.println(dayListCount);
        for (int i = 0; i < times.size(); i++) {
            for (int a = 0; a < dayListCount.size(); a++) {
                if (times.get(i).equals(dayListCount.get(a))) {
                    times.remove(i);
                }
            }
        }
        return times;
    }


    @Override
    public List<String> getAdvanceCards() {

        String userId = getUserId();
        List<String> times = DateUtils.fourDayAfter();
        DbCardQueryCriteria criteria = new DbCardQueryCriteria();
        criteria.setUserId(userId);
        criteria.setTimes(times);
        //查询出有打卡的日期
        List<String> dayListCount = baseMapper.getDayListCount(criteria);
        // System.out.println(dayListCount);
        for (int i = 0; i < times.size(); i++) {
            for (int a = 0; a < dayListCount.size(); a++) {
                if (times.get(i).equals(dayListCount.get(a))) {
                    times.remove(i);
                }
            }
        }
        return times;
    }

    //算第一天 到后面连续几天
    @Override
    public Integer getUserAdvanceDays() {
        List<String> times = DateUtils.fourDayAfter();
        String userId=getUserId();
        DbCardQueryCriteria criteria=new DbCardQueryCriteria();
        criteria.setUserId(userId);
        criteria.setTimes(times);
        //查询出有打卡的日期
        Map<LocalDate, Integer> map = new LinkedHashMap<>();
        LocalDate first = null;
        Integer result = 0;
        List<String> dayListCount = baseMapper.getDayListCount(criteria);

//        List<String> dayListCount = new ArrayList<>();
//        dayListCount.add("2024-09-21");
//        dayListCount.add("2024-09-22");
//        dayListCount.add("2024-09-23");
//        dayListCount.add("2024-09-24");

        if (UtilValidate.isEmpty(dayListCount)) {
            return result;
        }
        if (UtilValidate.isNotEmpty(dayListCount) && !dayListCount.get(0).equals(times.get(0))) {
            return result;
        }

        String startDateStr = dayListCount.get(0);
        String[] start_arr = startDateStr.split("-");

        LocalDate startDate = LocalDate.of(Integer.parseInt(start_arr[0]), Integer.parseInt(start_arr[1]), Integer.parseInt(start_arr[2]));
        if (startDateStr.equals(times.get(0))) {
            first = startDate;
            map.put(first, 1);
        }
        for (int b = 0; b < dayListCount.size(); b++) {
            String endDateStr = dayListCount.get(b);
            String[] end_arr = endDateStr.split("-");
            LocalDate endDate = LocalDate.of(Integer.parseInt(end_arr[0]), Integer.parseInt(end_arr[1]), Integer.parseInt(end_arr[2]));
            if (startDate.plusDays(1).isEqual(endDate)) {
                if (map.containsKey(first)) {
                    Integer integer = map.get(first);
                    map.put(first, integer + 1);
                }
                startDate = startDate.plusDays(1);
            }

        }

//        System.out.println(map);
        result = map.get(first);
        return result;
    }

    @Override
    public Integer getRangeDateCards(String startDate, String endDate) {
        Integer num=0;
        boolean result = false;
        //列出 不含 起始和结束 的日期数组
        List<String> times = DateUtils.getRangeDateCards(startDate, endDate, 3);

        String userId = getUserId();
        String userName = getUserName();
//        DbUserAdvanceDateQueryCriteria criteria = new DbUserAdvanceDateQueryCriteria();
//        criteria.setUserId(userId);
//        criteria.setTimes(times);

        DbUserAdvanceDateQueryCriteria c2 = new DbUserAdvanceDateQueryCriteria();
        c2.setUserId(userId);
        c2.setDay(endDate);
        List<DbUserAdvanceDate> endDates = dbUserAdvanceDateService.queryAll(c2);
        if(UtilValidate.isEmpty(endDates)){
            //插入结束日期
            DbUserAdvanceDate advanceDate=new DbUserAdvanceDate();
            advanceDate.setDay(endDate);
            advanceDate.setUserId(userId);
            advanceDate.setUserName(userName);
            dbUserAdvanceDateService.addOneFn(advanceDate);
            num=1;
        }

        return num;

        //查询出有打卡的日期
//        List<UserAdvanceDateDto> dayListCount = dbUserAdvanceDateService.getDayListCount(criteria);
//        if (times.size() == dayListCount.size()) {
//            result = true;
//        }
//        if(result){
//            List<UserAdvanceDateDto> list=new ArrayList<>();
//            dayListCount.forEach(r->{
//                if(UtilValidate.isEmpty(r.getAdvanceDateId())){
//                    list.add(r);
//                }
//            });
//            num=list.size()+1;
//            dbUserAdvanceDateService.addBatchFn(list);
//        }
//
//        return num;
    }


    @Override
    public Integer getRangeDateNowCard(String startDate) {
        DbUserAdvanceDateQueryCriteria criteria = new DbUserAdvanceDateQueryCriteria();
        String userId = getUserId();
        criteria.setUserId(userId);
        criteria.setStartTime(startDate);
        Integer result=0;
        List<UserAdvanceDateDto> dayListCount = dbUserAdvanceDateService.getDayListCount(criteria);

        List<String> ts = DateUtils.fourDayAfter();
        String firstDate=ts.get(0);//明天
        if(UtilValidate.isNotEmpty(dayListCount)){
            if(!firstDate.equals(dayListCount.get(0).getDay())){
                return result;
            }
            List<String> times = DateUtils.getRangeDateCards(firstDate, dayListCount.get(dayListCount.size()-1).getDay(), 0);
            result=times.size();
        }


//        List<String> times = DateUtils.getRangeDateCards(startDate, dayListCount, 0);

        return result;
    }

    @Override
    public RankingTableUserDto dutyTableList(RankingUserQueryCriteria criteria, YmPageDto pageDto) {
        RankingTableUserDto result = new RankingTableUserDto();
        try {
            Date now = new Date();
            String year;
            if (UtilValidate.isEmpty(criteria.getYear())) {
                 year = DateKit.dateFormat(now, "yyyy");
                criteria.setYear(year);
            }else{
                Date date = DateKit.dateFormat(criteria.getYear());
                 year = DateKit.dateFormat(date, "yyyy");
                criteria.setYear(year);
            }
            List<RankingMonthDto> monthDtos = baseMapper.rankingMonths(criteria);
            criteria.setList(monthDtos);
            getPage(pageDto);
            List<RankingUserDto> datas = baseMapper.dutyTableList(criteria);
            for (RankingUserDto userDto : datas) {
                BigDecimal totalRealNum = BigDecimal.ZERO;//实到合计
                BigDecimal totalShouldNum = BigDecimal.ZERO;//24天合计
                BigDecimal totalAllNum = BigDecimal.ZERO;//30天合计

                BigDecimal shouldRate=null;//个人 24天完成率
                BigDecimal ALLRate=null;//个人 30天完成率
                Class<RankingUserDto> aClass = RankingUserDto.class;

                for (RankingMonthDto monthDto : monthDtos) {
                    String year_str = monthDto.getMonth().split("-")[0];
                    int let_year = Integer.valueOf(year_str);
                    int let_month = Integer.valueOf(monthDto.getMonthNo());

                    YearMonth yearMonth = YearMonth.of(let_year, let_month);
                    int daysInMonth = yearMonth.lengthOfMonth();

                    //反射注入
                    //这个月天数
//                    Class<RankingUserDto.class> aClass = userDto.getClass();
                    Method method = aClass.getMethod("setDays" + monthDto.getMonthNo(), Integer.class);
                    method.invoke(userDto, Integer.valueOf(daysInMonth));

                    DbCardQueryCriteria userDaysCountQuery = new DbCardQueryCriteria();
                    userDaysCountQuery.setUserId(userDto.getUserId());
                    userDaysCountQuery.setMonth(monthDto.getMonth());
                    Long dayCount = baseMapper.getDayCount(userDaysCountQuery);
                    //实到天数
                    if (UtilValidate.isNotEmpty(dayCount)) {
                        Method method2 = aClass.getMethod("setRealNum" + monthDto.getMonthNo(), Integer.class);
                        method2.invoke(userDto, Integer.valueOf(dayCount.intValue()));
                        totalRealNum=totalRealNum.add(new BigDecimal(dayCount));

                    }
                    //应到天数
                    Method method3 = aClass.getMethod("setShouldNum" + monthDto.getMonthNo(), Integer.class);
                    method3.invoke(userDto, Integer.valueOf(24));
                    totalShouldNum=totalShouldNum.add(new BigDecimal(24));
                    totalAllNum=totalAllNum.add(new BigDecimal(daysInMonth));
                    //满勤
                    Integer isFull = 0, isAll = 0;
                    if (dayCount >= 24) {
                        isFull = 1;
                    }
                    if (dayCount >= daysInMonth) {
                        isAll = 1;
                    }
                    Method method4 = aClass.getMethod("setIsFull" + monthDto.getMonthNo(), Integer.class);
                    //这几个月全部算满勤

                    method4.invoke(userDto, isFull);
                    Method method5 = aClass.getMethod("setIsAll" + monthDto.getMonthNo(), Integer.class);
                    method5.invoke(userDto, isAll);
                }
//                log.info("---"+userDto.getUserName()+"--24d："+totalRealNum.doubleValue()+"--30d:"+totalAllNum.doubleValue());
                //24天完成率
                shouldRate=totalRealNum.divide(totalShouldNum,2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                if(shouldRate.compareTo(new BigDecimal(100))>0){
                    shouldRate=new BigDecimal(100);
                }
                //30天完成率
                ALLRate=totalRealNum.divide(totalAllNum,2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));

                userDto.setShouldRate(shouldRate.doubleValue()+"%");
                userDto.setAllRate(ALLRate.doubleValue()+"%");

            }
            PageInfo<RankingUserDto> pageInfo = new PageInfo<>(datas);
            TableList<RankingUserDto> tableList = new TableList<>(pageInfo);


            result.setMonths(monthDtos);
            result.setDataList(tableList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return result;
    }


    @Override
    public TableList<UserTimeCountDto> getUserYearCount(DbCardQueryCriteria criteria, YmPageDto ymPage) {
        getPage(ymPage);
        List<UserTimeCountDto> maps = getYearCount(criteria);
        PageInfo<UserTimeCountDto> pageInfo = new PageInfo<>(maps);
        TableList<UserTimeCountDto> tableList = new TableList<>(pageInfo);
        return tableList;
    }

    @Override
    public TableList<UserTimeCountDto> getUserMonthCount(DbCardQueryCriteria criteria, YmPageDto ymPage) {
        getPage(ymPage);
        List<UserTimeCountDto> maps = getMonthCountList(criteria);
        PageInfo<UserTimeCountDto> pageInfo = new PageInfo<>(maps);
        TableList<UserTimeCountDto> tableList = new TableList<>(pageInfo);
        return tableList;
    }

    @Override
    public List<UserTimeCountDto> getYearCount(DbCardQueryCriteria criteria) {
        List<String> years = baseMapper.getYearCount(criteria);
        List<UserTimeCountDto> list=new ArrayList<>();
        for(String year: years){
            DbUserNoteQueryCriteria noteQueryCriteria=new DbUserNoteQueryCriteria();
            noteQueryCriteria.setUserId(criteria.getUserId());
            noteQueryCriteria.setYear(year);
            BigDecimal userDurations = dbUserNoteService.getUserDurations(noteQueryCriteria);
            UserTimeCountDto dto=new UserTimeCountDto();
            dto.setDate(year);
            if(UtilValidate.isNotEmpty(userDurations)){
                BigDecimal divide = userDurations.divide(new BigDecimal(60), 2, BigDecimal.ROUND_HALF_UP);
                dto.setDuration(divide);
            }
            list.add(dto);
        }
        return list;
    }

    @Override
    public List<UserTimeCountDto> getMonthCountList(DbCardQueryCriteria criteria) {
        List<String> months = baseMapper.getMonthCountList(criteria);
        List<UserTimeCountDto> list=new ArrayList<>();
        for(String month: months){
            DbUserNoteQueryCriteria noteQueryCriteria=new DbUserNoteQueryCriteria();
            noteQueryCriteria.setUserId(criteria.getUserId());
            noteQueryCriteria.setMonth(month);
            BigDecimal userDurations = dbUserNoteService.getUserDurations(noteQueryCriteria);
            UserTimeCountDto dto=new UserTimeCountDto();
            dto.setDate(month);
            if(UtilValidate.isNotEmpty(userDurations)){
                //查出来的是秒 ，要换算成分钟
                BigDecimal divide = userDurations.divide(new BigDecimal(60), 2, BigDecimal.ROUND_HALF_UP);
                dto.setDuration(divide);
            }
            list.add(dto);
        }
        return list;
    }
}
